<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>取消请求</title>
  </head>
  <body>
    <button onclick="getProducts1()">获取商品列表1</button><br />
    <button onclick="getProducts2()">获取商品列表2</button><br />
    <button onclick="cancelReq()">取消请求</button><br />

    <script src="https://cdn.bootcss.com/axios/0.19.0/axios.js"></script>
    <script>
      let cancel;

      // 添加请求拦截器
      axios.interceptors.request.use((config) => {
        if (typeof cancel === "function") {
          cancel("取消请求");
        }

        config.cancelToken = new CancelToken(function executor(c) {
          // executor 函数接收一个 cancel 函数作为参数
          cancel = c;
        });
        return config;
      });

      // 添加响应连接器
      axios.interceptors.response.use(
        (response) => {
          cancel = null;
          return response;
        },
        (error) => {
          if (axios.isCancel(error)) {
            // 异步执行，这里不需要将cancel置为null，他会在其他请求中重新赋值
            // cancel = null;
            console.log("请求失败了", error.message);
            // 中端promise链
            return new Promise(() => {});
          } else {
            cancel = null;
            console.log("请求失败了", error.message);
            // 向下处理
            // throw error
            return Promise.reject(new Error(error));
          }
        }
      );

      function getProducts1() {
        axios({ url: "http://localhost:4000/products1" })
          .then((response) => {
            console.log("请求1成功了".response);
          })
          .catch((error) => {
            console.log("请求1失败了", error.message);
          });
      }

      function getProducts2() {
        axios({ url: "http://localhost:4000/products2" })
          .then((response) => {
            console.log("请求2成功了".response);
          })
          .catch((error) => {
            console.log("请求2失败了", error.message);
          });
      }

      function cancelReq() {
        if (typeof cancel === "function") {
          cancel("强制取消请求");
        } else {
          console.log("没有可取消的请求");
        }
      }
    </script>
  </body>
</html>
